package cn.siriusbot.siriuspro.bot.api.impl.bot;

import cn.siriusbot.siriuspro.bot.api.ResourceApi;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Path;

@Component
@Data
@Log4j2
public class ResourceApiImpl implements ResourceApi {

    String packageName;

    String filePath;

    public ResourceApi build(String packageName) {
        ResourceApiImpl resourceApi = new ResourceApiImpl();
        BeanUtils.copyProperties(this, resourceApi);
        resourceApi.packageName = packageName;
        resourceApi.initDir();
        return resourceApi;
    }

    /**
     * 初始化应用目录空间
     */
    private void initDir() {
        try {
            String filePath = Path.of(System.getProperty("user.dir") + "/cache").toString();
            File file = new File(filePath);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    throw new RuntimeException("创建应用目录失败");
                }
            }
            filePath = Path.of(filePath + "/" + packageName).toString();
            file = new File(filePath);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    throw new RuntimeException("创建应用目录失败");
                }
            }
            this.filePath = filePath;
        } catch (Throwable e) {
            this.filePath = null;
            log.error("创建应用目录失败", e);
        }
    }

    /**
     * 获取一个文件对象
     */
    @Override
    public File getFile(String name) {
        if (this.filePath == null) {
            return null;
        }
        return Path.of(this.filePath + "/" + name).toFile();
    }
}
